<template>
  <div>
    <div class="page">
      <article class="container">
        <header class="header">
          <div class="deahtop">
            <a href="#">
              <i class="hl iconfont icon-zuojiantou"></i>
            </a>
            <div class="titl">
              <p>购物车</p>
            </div>
            <a href="#">
              <i class="hr iconfont icon-shenglvehao"></i>
            </a>
          </div>
          <div class="deahnav">
            <ul>
              <li class="deactive">全部({{goodsList.length}})</li>
              <li>降价(4)</li>
              <li>热卖(2)</li>
              <li>
                分类
                <i class="jian iconfont icon-shangxia"></i>
              </li>
            </ul>
          </div>
        </header>
        <article class="shopcon">
          <section class="shoptop" v-if="userInfo.token">
            <form action="#" >
              <ul class="shopform" >
                <li
                  class="shopactive"
                  v-for="(item, index) in goodsList"
                  :key="item.id"
                >
                  <div class="titleleft">
                      <input type="checkbox" v-model="item.isTrue" class="w3" @change="changeOne()">
                    <div class="toimg">
                      <img :src="$pre + item.img" alt="" />
                    </div>
                  </div>
                  <div class="titleright">
                    <p>{{ item.goodsname }}</p>
                    <div class="sele">
                      <select>
                        <option value="">桔色果汁[20#]</option>
                      </select>
                      <i class="seo iconfont icon-xia"></i>
                    </div>
                    <p>
                      <span>&yen;{{ item.price }} </span>
                      <span>距离加入降&yen;{{ item.price + 5 }}</span>
                    </p>
                    <p class="opop">
                      <button @click="pre(item.id, index)">-</button>
                      <span class="bnum">{{item.num}}</span>
                      <button @click="add(item.id, index)">+</button>
                      <i class="la iconfont icon-lajitong" @click="del(item.id,index)"></i>
                    </p>
                  </div>
                </li>
              </ul>
            </form>
          </section>
        <van-empty description="您还未登录，请先登录" v-else>
          <van-button round type="danger" class="bottom-button" @click="$router.push('/sign')">登录</van-button>
        </van-empty>
        </article>
      </article>
        <div id="close">
        <p>
          <input type="checkbox" v-model="checkAll" @change="changeAll()">
          <span class="center"><em>合计</em>已免运费</span
          ><span><b>￥{{priceAll}}</b>已优惠￥{{discount}}元</span>
        </p>
        <i @click="goOrder()">结算</i>
      </div>
    </div>
  </div>
</template>
<script>
import { cartlist,cartedit,cartdelete} from "../../request/api.js";
 import { Toast } from 'vant';
export default {
  data() {
    return {
      userInfo: sessionStorage.getItem("user")
        ? JSON.parse(sessionStorage.getItem("user"))
        : {},
      // 存放商品信息
      goodsList: [],
      // 用来标识全选的状态
      checkAll: false,
    };
  },
  methods: {
    add(id,index){
      // 商品最大数量为8
      if(this.goodsList[index].num <= 7){
        cartedit({
        id:id,
        type:2
      }).then(res=>{
        if(res.data.code == 200){
          this.goodsList[index].num ++
        }
      })
      }
    },
    // 点击减少
    pre(id,index){
      // 如果当前商品的数量大于1的时候我们才能掉借口，因为要保证商品的最小num为1
      if(this.goodsList[index].num > 1){
        cartedit({
        id:id,
        type:1
      }).then(res=>{
        // 我们正常的逻辑就是添加之后重新请求列表数据，但是我们要考虑一下性能问题，假设我的列表数据很多的话，我们每一次修改之后都有要重新请求列表数据，这样就有一个资源浪费的问题。我们可以将这个文件简化处理：每次编辑成功之后在前台页面中将这个num减1就好了
        if(res.data.code == 200){
          this.goodsList[index].num --
        }
      })
      }
    },
    // 当每一条商品的复选框发生变化
    changeOne(){
      this.checkAll = this.goodsList.every(item=>{
        return item.isTrue
      })
    },
    changeAll(){
          this.goodsList.map(item=>{
              item.isTrue = this.checkAll
          })
      },
    //删除
    del(id,index){
        console.log(id,index)
        console.log(this.form)
        cartdelete({id:id}).then(res=>{
            if(res.data.code == 200){
                this.goodsList.splice(index,1)
                Toast.success(res.data.msg);
            }else{
                 Toast.fail(res.data.msg)
            }
          
        })
    },
    //结算
    goOrder(){
      let countmoney = this.priceAll
      let countnumber = this.discount/5
      let arr = []
      this.goodsList.forEach(item=>{
          if(item.isTrue){
              arr.push(item.id)
        }
      })
      let idstr = arr.join(",")
      console.log(idstr)
      //countmoney:合集总价
      //countnumber:商品数量
      //idstr:选中的商品
      this.$router.push("/order")
      this.$cookies.set("countmoney",countmoney)
      this.$cookies.set("countnumber",countnumber)
      this.$cookies.set("idstr",idstr)
    }
  },
  components: {},
  mounted() {
    if (this.userInfo.token) {
      cartlist({
        uid: this.userInfo.uid,
      }).then((res) => {
        let arr = res.data.list ? res.data.list : [];
        arr.map((item) => {
          item.isTrue = false;
        });
        this.goodsList = arr;
      });
    }
  },
  computed:{
       priceAll(){
      // 假设总价为0
      let sum = 0
      this.goodsList.forEach(item=>{
        if(item.isTrue){
          sum += item.price * item.num
        }
      })
      return sum
    },
    // 优惠的金额
    discount(){
      // 假设一共优惠了0元
      let sum = 0
      this.goodsList.forEach(item=>{
        if(item.isTrue){
          sum += item.num * 5
        }
      })
      return sum
    }
  },
  destroyed() {},
};
</script>
<style scoped>
@import url(../../assets/css/public.css);
@import url(../../assets/css/shopping_cart.css);
@import url(../../assets/css/product_details.css);
button {
  width: 0.5rem;
  height: 0.5rem;
  text-align: center;
  font-size: .5rem;
}
.bnum {
  width: 0.3rem;
  height: 0.4rem;
  background: #f2f2f2;
  text-align: center;
  line-height: 0.4rem;
  margin: 0 0.12rem;
  font-size: .4rem;
}
#close {
  border-top: 1px solid #cccccc;
  display: flex;
  height: 0.98rem;
  background: #fff;
  position: absolute;
  left: 0;
  bottom: 100px;
}
#close p {
  width: 5.3rem;
  height: 0.98rem;
  padding: 0 0.12rem 0 0.1rem;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  color: #333333;
  font-size: 0.3rem;
}
#close p i {
  width: 0.32rem;
  height: 0.32rem;
  border: 1px solid #999999;
  border-radius: 50%;
  background: #f2f2f2;
  margin-right: 0.1rem;
}
#close p .center {
  margin: 0 0.1rem 0 0.8rem;
}
#close p span {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #a5a5a5;
  font-size: 0.18rem;
}
#close p span em {
  font-size: 0.3rem;
  color: #333333;
}
#close p span b {
  font-size: 0.3rem;
  color: #ff6040;
}
#close i {
  width: 2.2rem;
  background: #ff6040;
  line-height: 0.98rem;
  text-align: center;
  color: #fff;
  font-size: 0.3rem;
  font-weight: bold;
}

</style>